package signal;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Emotion implements Runnable {

    private Lock lock;
    private Condition smileCondition;
    private Condition amazeCondition;

    public Emotion(Lock lock) {
        this.lock = lock;
        smileCondition = this.lock.newCondition();
        amazeCondition = this.lock.newCondition();
    }

    @Override
    public void run() {
        try {
            lock.lock();
            if ("^_^".equals(Thread.currentThread().getName())) {

                for (int i = 1; i <= 50; i++) {
                    System.out.println("^_^");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (i % 10 == 0 && i < 50) {
                        amazeCondition.signalAll();
                        try {
                            smileCondition.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (i == 50) {
                        amazeCondition.signalAll();
                    }
                }

            } else {
                for (int i = 1; i <= 50; i++) {
                    System.out.println("@_@");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (i % 10 == 0 && i < 50) {
                        smileCondition.signalAll();
                        try {
                            amazeCondition.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (i == 50) {
                        smileCondition.signalAll();
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //释放锁
        }
    }
}
